/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package controller

import (
	"icep/auth"
	"icep/common/constant"
	"icep/common/http"

	"github.com/emicklei/go-restful"
)

func (ic *IcepController) GetRealNameOrg(req *restful.Request, resp *restful.Response) {
	// 获取用户类型，如果不是企业用户则失败
	currentUserType := auth.GetCurrentUserType(req)
	if currentUserType != constant.UserTypeOrg {
		http.Failed(resp, "用户无权限！")
		return
	}
	id := auth.GetCurrentUserId(req)
	detail, err := ic.IcepService.GetRealNameOrg(id)
	if err != nil {
		log.Errorf("查询失败: %v", err)
		http.Failed(resp, err.Error())
		return
	}
	http.OkWithData(resp, "查询成功", detail)
}

func (ic *IcepController) CreateRealNameOrg(req *restful.Request, resp *restful.Response) {
	currentUserType := auth.GetCurrentUserType(req)
	if currentUserType != constant.UserTypeOrg {
		http.Failed(resp, "用户无权限！")
		return
	}
	userId := auth.GetCurrentUserId(req)
	orgName := req.QueryParameter("orgName")
	orgCode := req.QueryParameter("orgCode")
	legalPersonName := req.QueryParameter("legalPersonName")
	legalPersonId := req.QueryParameter("legalPersonId")
	orgLicense, errs := http.ReadFile(req, "orgLicense")
	if errs != nil {
		log.Errorf("read orgLicense error: %s", errs)
		http.Failed(resp, "读取文件失败")
		return
	}
	idCardFront, errs := http.ReadFile(req, "idCardFront")
	if errs != nil {
		log.Errorf("read idCardFront error: %s", errs)
		http.Failed(resp, "读取文件失败")
		return
	}
	idCardBack, errs := http.ReadFile(req, "idCardBack")
	if errs != nil {
		log.Errorf("read idCardBack error: %s", errs)
		http.Failed(resp, "读取文件失败")
		return
	}

	if orgName == "" || orgCode == "" || legalPersonName == "" || legalPersonId == "" {
		log.Errorf("orgName or orgCode or legalPersonName or legalPersonId all empty!")
		http.Failed(resp, "请求参数不合法！")
		return
	}

	err := ic.IcepService.CreateRealNameOrg(userId, orgName, orgCode, legalPersonName, legalPersonId, orgLicense, idCardFront, idCardBack)
	if err != nil {
		log.Errorf("create RealNameOrg error: %s", err)
		http.Failed(resp, err.Error())
		return
	}
	http.Ok(resp, "实名认证成功")
}
